import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_first_one/api/file.dart';
import 'package:flutter_first_one/api/story.dart';
import 'package:flutter_first_one/components/story_card.dart';
import 'package:get/get.dart';
import 'package:carousel_slider/carousel_slider.dart';
import 'package:flutter_first_one/custom_behavior/scroll_behavior.dart';

class Home extends StatefulWidget {
  const Home({super.key});

  @override
  // ignore: library_private_types_in_public_api
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  List<dynamic> storyType = [
    {
      'name': '热门AI故事',
      'params': {
        'dataType': 2,
        'sort': [
          {'key': 'forwardNum', 'value': 'desc'}
        ]
      },
      'list': []
    },
    {
      'name': '重磅新品',
      'params': {
        'dataType': 2,
        'sort': [
          {'key': 'id', 'value': 'desc'}
        ]
      },
      'list': []
    },
    {
      'name': '精品推荐',
      'params': {
        'dataType': 2,
        'sort': [
          {
            'key': 'collectNum',
            'value': 'desc',
          }
        ]
      },
      'list': []
    },
    {
      'name': '剧集故事',
      'params': {
        'dataType': 1,
        'sort': [
          {
            'key': 'forwardNum',
            'value': 'desc',
          }
        ]
      },
      'list': []
    }
  ];

  getStoryList() {
    storyType.forEach((item) async {
      var res = await StoryApi.storyInfo(
          {'pageNo': 1, 'pageSize': 8, ...item['params'] as dynamic});
      setState(() {
        item['list'] = res.data['list'];
      });
    });
  }

  @override
  void initState() {
    super.initState();
    getStoryList();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('儿时故事'),
      ),
      body: CusScrollBehavior(
        child: ListView(
          children: [
            const Banner(),
            ...storyType
                .map((e) => StoryList(
                      title: e['name'].toString(),
                      list: e['list'] as List<dynamic>,
                    ))
                .toList()
          ],
        ),
      ),
    );
  }
}

class Banner extends StatefulWidget {
  const Banner({super.key});

  @override
  // ignore: library_private_types_in_public_api
  _BannerState createState() => _BannerState();
}

// 轮播图
class _BannerState extends State<Banner> {
  final RxList<Widget> _adList = <Widget>[].obs;

  _getAdData() async {
    final res = await StoryApi.adInfo({'pageNo': 1, 'pageSize': 3});
    _adList.value = (res.data['list'] as List).map((e) {
      return Container(
        decoration: BoxDecoration(
            image: DecorationImage(
                image: NetworkImage(
                  File.imageUrl(e['advertisementUrl']),
                ),
                fit: BoxFit.cover),
            borderRadius: const BorderRadius.only(
                bottomLeft: Radius.circular(20),
                bottomRight: Radius.circular(20))),
      );
    }).toList();
  }

  @override
  void initState() {
    super.initState();
    _getAdData();
  }

  @override
  Widget build(BuildContext context) {
    return Obx(() => CarouselSlider(
          options: CarouselOptions(
              height: 200.0,
              viewportFraction: 1,
              // disableCenter: true,
              autoPlay: true,
              padEnds: false),
          items: _adList.toList(),
        ));
  }
}

class StoryList extends StatelessWidget {
  final String? title;
  final List<dynamic>? list;
  const StoryList({super.key, required this.title, required this.list});

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        const SizedBox(
          height: 20,
        ),
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            const Icon(
              Icons.star_outlined,
              color: Color.fromRGBO(255, 152, 44, 1),
              size: 20,
            ),
            const SizedBox(
              width: 3,
            ),
            Text(
              title.toString(),
              style: const TextStyle(fontSize: 18),
            ),
            const Expanded(flex: 1, child: Text('')),
            GestureDetector(
              onTap: () {
                Get.toNamed('/more', arguments: {'key': title});
              },
              child: const Text(
                '更多故事',
                style: TextStyle(color: Color.fromRGBO(205, 170, 154, 1)),
              ),
            ),
            const Icon(
              Icons.arrow_forward_ios_sharp,
              color: Color.fromRGBO(205, 170, 154, 1),
              size: 16,
            )
          ],
        ),
        const SizedBox(
          height: 10,
        ),
        SizedBox(
          height: 280,
          child: ListView.builder(
            scrollDirection: Axis.horizontal,
            itemCount: list?.length,
            itemBuilder: (context, index) {
              return SizedBox(
                width: 180,
                child: StoryCard(item: list?[index]),
              );
            },
          ),
        )
      ],
    );
  }
}
